import Vue from 'vue'
import Vuex from 'vuex'
import api from '@/common/api.js'
import wishModel from './model/wish.js'
Vue.use(Vuex)

const store = new Vuex.Store({
	modules:{
		wish:wishModel
	},
	state: {
		hasBind: false,
		userInfo: {},
		coinName:'心愿值'
	},
	getters: {
		coinNum: state => {
		  return Number(state.userInfo.wish_coin_num)||0
		},
		hasBind: state => {
			return state.hasBind
		},
		userInfo: state =>{
			return state.userInfo
		}
	},
	mutations: {
		// login(state, provider) {
			
		// 	state.hasLogin = true;
		// 	state.userInfo = provider;
		// 	uni.setStorage({//缓存用户登陆状态
		// 	    key: 'userInfo',  
		// 	    data: provider  
		// 	}) 
		// 	console.log(state.userInfo);
		// },
		setBind(state){
			state.hasBind=true
		},
		logout(state) {
			state.hasLogin = false;
			state.userInfo = {};
			uni.removeStorage({  
                key: 'userInfo'  
            })
		},
		setUserInfo(state,data){
			state.userInfo=data
		}
	},
	actions: {
		login({state,commit}){
			let token=uni.getStorageSync('token')
			let tokenDeadline=uni.getStorageSync('tokenDeadline')
			return new Promise((resolve,reject)=>{
				let now=+new Date()
				if(token&&tokenDeadline-now>0){
					resolve(token)
					return
				}
				uni.login({
				  success:async ({code})=> {
					let {query}=wx.getLaunchOptionsSync()
					let referCode=query.refer_code
					let res=await api.login({code,refer_code:referCode})
					token=res.AUTHORIZATION
					tokenDeadline=now+29*24*60*60*1000 // 后台30天过期,前端提前一天过期
					uni.setStorage({key:'token',data:token})
					uni.setStorage({key:'tokenDeadline',data:tokenDeadline})
					resolve(token)
				  },
				  fail:()=>{
					  reject()
				  }
				})
			})
		},
		bind({state,commit,},data){
			return new Promise(async(resolve,reject)=>{
				let res=await api.bind({...data})
				commit('setBind')
				resolve()
			})
		},
		async getUserInfo({state,commit},params){
			const data = await api.getUserInfo({},params)
			if(data.is_bind===1){
				commit('setBind')
			}
			commit('setUserInfo',data)
			return data
		},
		async getPopups(){
			const data = await api.getPopups()
			return data
		}
	}
})

export default store
